package Thread;

/**
 * 两个线程交替打印数字，一个打印奇数，另一个打印偶数，1000以内数子:
 * <p>
 * 创建两个线程，一个线程负责打印奇数，另一个线程打印偶数，两个线程竞争同一个对象锁，每次打印一个数字后释放锁，
 * 然后另一个线程拿到锁打印下一个数字。
 */
public class ThreadPrentClass {

    private static volatile int num = 0;

    Object object = new Object();


    public static void main(String[] args) {

        ThreadPrentClass threadPrentClass = new ThreadPrentClass();

        new Thread(() -> {

            try {
                threadPrentClass.printOnAndEvent();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "Thread1").start();


        new Thread(() -> {
            try {
                threadPrentClass.printOnAndEvent();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "Thread2").start();

        new Thread(() -> {
            try {
                threadPrentClass.printOnAndEvent();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "Thread3").start();

    }


    public void printEvenNumber() throws InterruptedException {
        while (num < 100) {

            synchronized (object) {
                if (num % 2 == 0) {
                    System.out.println(Thread.currentThread().getName() + ":" + num++);
                    //  this.notify();
                }
            }

        }
    }


    public void printOnEvenNumber() throws InterruptedException {
        while (num < 100) {

            synchronized (object) {

                if (num % 2 == 1) {

                    System.out.println(Thread.currentThread().getName() + ":" + num++);

                }


            }
        }


    }


    public void printOnAndEvent() throws InterruptedException {
        while (num <=100) {
            synchronized (object){
                System.out.println(Thread.currentThread().getName()+":"+num++);
                object.notify();
                if(num<=100){
                    object.wait();
                }
            }


        }
    }
}
